package io.wit.modules.wit.controller;

import io.wit.common.annotation.SysLog;
import io.wit.common.utils.PageUtils;
import io.wit.common.utils.Querys;
import io.wit.common.utils.R;
import io.wit.common.validator.Assert;
import io.wit.config.ConfigFile;
import io.wit.modules.sys.entity.SysItemEntity;
import io.wit.modules.sys.entity.SysUserEntity;
import io.wit.modules.sys.service.SysItemService;
import io.wit.modules.sys.service.SysUserService;
import io.wit.modules.sys.shiro.ShiroUtils;
import io.wit.modules.wit.entity.EmployeeEntity;
import io.wit.modules.wit.service.EmployeeService;
import io.wit.tool.ToolClient;
import org.apache.commons.lang.RandomStringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 员工档案
*/
@RestController
@RequestMapping("employee")
public class EmployeeController {

    @Autowired
	private EmployeeService employeeService;

    @Autowired
    private SysItemService SysItemService;

    @Autowired
    private SysUserService sysUserService;

    @Value("${role_value2}")
    private int roleValue2;
	
	/**
	 * 列表
	*/
	@RequestMapping("/list")
	@RequiresPermissions("employee:list")
	public R list(@RequestParam Map<String, Object> params){
        final SysUserEntity user = ShiroUtils.getUserEntity();
        //查询列表数据
        final Querys query = new Querys(params);
        if(!ConfigFile.superUser.equals(user.getUsername())){
            final Long subjectId = user.getSubjectId();
            if(subjectId != null){
                query.put("subjectId",subjectId);
            }else{
                final PageUtils page = new PageUtils(new ArrayList<>(),0,query.getLimit(), query.getPage());
                return R.ok().put("page",page).put("msg","当前账号尚未添加经营主体");
            }
        }
		final List<EmployeeEntity> employeeList = employeeService.queryList(query);
		final int total = employeeService.queryTotal(query);
		PageUtils pageUtil = new PageUtils(employeeList, total, query.getLimit(),query.getPage());
		return R.ok().put("page",pageUtil);
	}
	
	/**
	 * 信息
	*/
	@RequestMapping("/info/{dataId}")
	@RequiresPermissions("employee:info")
	public R info(@PathVariable("dataId") Long dataId){
		final EmployeeEntity employee = employeeService.queryObject(dataId);
		return R.ok().put("employee", employee);
	}
	
	/**
	 * 删除
	*/
	@RequestMapping("/delete")
	@RequiresPermissions("employee:delete")
	public R delete(@RequestBody Long[] dataIds){
		employeeService.deleteBatch(dataIds);
		return R.ok();
	}

    @GetMapping("/getTypeEducation")
    public void getTypeEducation(final HttpServletResponse response){
        final String json = employeeService.getTypeEducation();
        ToolClient.responseJson(json,response);
    }

    @GetMapping("/get/{dataId}")
    public void get(@PathVariable("dataId")final Long dataId,final HttpServletResponse response){
        ToolClient.responseJson(employeeService.queryMap(dataId),response);
    }

    /**
     * 保存
    */
    @PostMapping("/save")
    @RequiresPermissions("employee:save")
    public void save(final HttpServletRequest request,final HttpServletResponse response){
        final SysUserEntity userEntity = filterHandle(response);
        if(userEntity == null) return;
        final String json = employeeService.saveEmployee(request);
        ToolClient.responseJson(json,response);
    }

    /**
     * 修改
     */
    @PostMapping("/update")
    @RequiresPermissions("employee:update")
    public void update(final HttpServletRequest request,final HttpServletResponse response){
        final SysUserEntity userEntity = filterHandle(response);
        if(userEntity == null) return;
        final String json = employeeService.editEmployee(request);
        ToolClient.responseJson(json,response);
    }

    /**
     * 重置用户密码
     */
    @SysLog("重置密码")
    @RequestMapping("/resetPassword")
    @RequiresPermissions("employee:update")
    public R resetPassword(final String userId,final String value){
        Assert.isBlank(userId,"账号不为能空");
        //新密码
        final String salt = RandomStringUtils.randomAlphanumeric(20);
        final String password = ShiroUtils.sha256(value,salt);
        //更新密码
        final int rows = sysUserService.resettingPassword(userId,password,salt);
        return R.execute(rows);
    }

    //获取角色类型
    @GetMapping("/getTypeRoles")
    public void getTypeRoles(final HttpServletResponse response){
        final SysUserEntity userEntity = filterHandle(response);
        if(userEntity == null) return;
        final List<SysItemEntity> list = SysItemService.getTypeRoles(userEntity.getSubjectId());
        ToolClient.responseJson(ToolClient.queryJson(list),response);
    }

    //获取经营主体部门
    @GetMapping("/getTypeDept")
    public void getTypeDept(final HttpServletResponse response){
        final SysUserEntity userEntity = filterHandle(response);
        if(userEntity == null) return;
        final List<SysItemEntity> list = SysItemService.getTypeDept(userEntity.getSubjectId());
        ToolClient.responseJson(ToolClient.queryJson(list),response);
    }

    protected SysUserEntity filterHandle(final HttpServletResponse response){
        final SysUserEntity user = ShiroUtils.getUserEntity();
        final Long roleId = user.getRoleId();
        if(roleId == null || roleId == roleValue2){
            final String json = ToolClient.createJsonFail("没有操作权限");
            ToolClient.responseJson(json,response);
            return null;
        }
        final Long subjectId = user.getSubjectId();
        if(subjectId == null){
            final String json = ToolClient.createJsonFail("请先添加经营主体");
            ToolClient.responseJson(json,response);
            return null;
        }
        return user;
    }
}